// utils/security.js
/**
 * 安全工具模块
 * 提供数据掩码、反欺诈检测、隐私保护等功能
 */

/**
 * 数据掩码工具
 */
const DataMask = {
  /**
   * 掩码手机号
   * @param {string} phone 手机号
   * @param {boolean} showPartial 是否显示部分数字
   * @returns {string} 掩码后的手机号
   */
  maskPhone(phone, showPartial = true) {
    if (!phone) return ''
    
    if (showPartial) {
      // 显示前3位和后2位：138****78
      return phone.replace(/(\d{3})\d{4}(\d{2})/, '$1****$2')
    } else {
      // 完全掩码：***-****-****
      return '***-****-****'
    }
  },

  /**
   * 掩码邮箱地址
   * @param {string} email 邮箱地址
   * @param {boolean} showPartial 是否显示部分字符
   * @returns {string} 掩码后的邮箱
   */
  maskEmail(email, showPartial = true) {
    if (!email) return ''
    
    const [localPart, domain] = email.split('@')
    if (!localPart || !domain) return email
    
    if (showPartial) {
      // 显示前2位和@域名：li****@example.com
      const maskedLocal = localPart.charAt(0) + 
        localPart.charAt(1) + 
        '****'
      return `${maskedLocal}@${domain}`
    } else {
      // 完全掩码：****@****
      return '****@****'
    }
  },

  /**
   * 掩码真实姓名
   * @param {string} realName 真实姓名
   * @param {boolean} showPartial 是否显示部分字符
   * @returns {string} 掩码后的姓名
   */
  maskRealName(realName, showPartial = true) {
    if (!realName) return ''
    
    if (showPartial) {
      // 显示姓氏和名字首字母：李*明 -> 李*
      if (realName.length === 2) {
        return realName.charAt(0) + '*'
      } else if (realName.length >= 3) {
        return realName.charAt(0) + '*'.repeat(realName.length - 2) + realName.charAt(realName.length - 1)
      }
      return realName
    } else {
      // 完全掩码
      return '*'.repeat(realName.length)
    }
  },

  /**
   * 掩码身份证号
   * @param {string} idCard 身份证号
   * @param {boolean} showPartial 是否显示部分数字
   * @returns {string} 掩码后的身份证号
   */
  maskIdCard(idCard, showPartial = true) {
    if (!idCard) return ''
    
    if (showPartial) {
      // 显示前6位和后4位：110101****1234
      return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1****$2')
    } else {
      // 完全掩码
      return '******************'
    }
  },

  /**
   * 掩码银行卡号
   * @param {string} cardNumber 银行卡号
   * @param {boolean} showPartial 是否显示部分数字
   * @returns {string} 掩码后的银行卡号
   */
  maskBankCard(cardNumber, showPartial = true) {
    if (!cardNumber) return ''
    
    if (showPartial) {
      // 显示前4位和后4位：6222 **** **** 1234
      return cardNumber.replace(/(\d{4})\d+(\d{4})/, '$1 **** **** $2')
    } else {
      // 完全掩码
      return '**** **** **** ****'
    }
  }
}

/**
 * 反欺诈检测工具
 */
const AntiFraud = {
  /**
   * 检测可疑文本内容
   * @param {string} text 待检测的文本
   * @returns {object} 检测结果
   */
  detectSuspiciousText(text) {
    if (!text) return { isSuspicious: false, reasons: [] }
    
    const suspiciousPatterns = [
      // 诈骗关键词
      /转账|汇款|充值|刷单|兼职|代刷|投资|理财|贷款|借钱/g,
      // 联系方式泄露
      /微信|QQ|电话|手机号|联系我/g,
      // 外部平台引导
      /淘宝|支付宝|银行|网站|链接|下载|注册/g,
      // 金钱相关
      /钱|元|块|万|收益|利润|返利|佣金/g,
      // 紧急词汇
      /紧急|急需|马上|立即|赶紧|快速/g
    ]
    
    const reasons = []
    let suspiciousScore = 0
    
    suspiciousPatterns.forEach((pattern, index) => {
      const matches = text.match(pattern)
      if (matches) {
        suspiciousScore += matches.length * (index + 1)
        switch (index) {
          case 0:
            reasons.push('包含诈骗相关关键词')
            break
          case 1:
            reasons.push('疑似泄露联系方式')
            break
          case 2:
            reasons.push('引导到外部平台')
            break
          case 3:
            reasons.push('涉及金钱交易')
            break
          case 4:
            reasons.push('使用紧急催促词汇')
            break
        }
      }
    })
    
    return {
      isSuspicious: suspiciousScore > 3,
      suspiciousScore,
      reasons,
      recommendation: suspiciousScore > 5 ? 'block' : suspiciousScore > 3 ? 'review' : 'allow'
    }
  },

  /**
   * 检测虚假信息
   * @param {object} userProfile 用户资料
   * @returns {object} 检测结果
   */
  detectFakeProfile(userProfile) {
    if (!userProfile) return { isFake: false, reasons: [] }
    
    const reasons = []
    let fakeScore = 0
    
    // 检查年龄是否合理
    if (userProfile.age && (userProfile.age < 18 || userProfile.age > 80)) {
      fakeScore += 2
      reasons.push('年龄信息异常')
    }
    
    // 检查资料完整度（过于完美的资料可能是虚假的）
    const completeness = this.calculateProfileCompleteness(userProfile)
    if (completeness === 100) {
      fakeScore += 1
      reasons.push('资料过于完美')
    }
    
    // 检查职业与年龄的匹配度
    if (userProfile.occupation && userProfile.age) {
      const highLevelJobs = ['CEO', '总经理', '董事长', '创始人', '总监']
      const hasHighLevelJob = highLevelJobs.some(job => 
        userProfile.occupation.includes(job)
      )
      
      if (hasHighLevelJob && userProfile.age < 25) {
        fakeScore += 3
        reasons.push('职业与年龄不匹配')
      }
    }
    
    // 检查教育背景
    if (userProfile.education && userProfile.graduationYear && userProfile.age) {
      const expectedAge = new Date().getFullYear() - userProfile.graduationYear + 22
      if (Math.abs(userProfile.age - expectedAge) > 5) {
        fakeScore += 2
        reasons.push('教育背景与年龄不符')
      }
    }
    
    return {
      isFake: fakeScore > 4,
      fakeScore,
      reasons,
      recommendation: fakeScore > 6 ? 'ban' : fakeScore > 4 ? 'flag' : 'normal'
    }
  },

  /**
   * 计算资料完整度
   * @param {object} profile 用户资料
   * @returns {number} 完整度百分比
   */
  calculateProfileCompleteness(profile) {
    const requiredFields = [
      'nickname', 'age', 'height', 'education', 'occupation', 
      'personalStatement', 'avatarConfig', 'interests'
    ]
    
    const completedFields = requiredFields.filter(field => {
      const value = profile[field]
      if (Array.isArray(value)) {
        return value.length > 0
      }
      return value && value.toString().trim().length > 0
    })
    
    return Math.round((completedFields.length / requiredFields.length) * 100)
  },

  /**
   * 检测账号行为异常
   * @param {object} behaviorData 行为数据
   * @returns {object} 检测结果
   */
  detectAbnormalBehavior(behaviorData) {
    if (!behaviorData) return { isAbnormal: false, reasons: [] }
    
    const reasons = []
    let abnormalScore = 0
    
    // 检查登录频率异常
    if (behaviorData.dailyLogins > 20) {
      abnormalScore += 2
      reasons.push('登录频率异常')
    }
    
    // 检查消息发送频率
    if (behaviorData.messagesPerHour > 50) {
      abnormalScore += 3
      reasons.push('消息发送频率过高')
    }
    
    // 检查点赞频率
    if (behaviorData.likesPerDay > 200) {
      abnormalScore += 2
      reasons.push('点赞频率异常')
    }
    
    // 检查设备切换频率
    if (behaviorData.deviceChangesPerWeek > 5) {
      abnormalScore += 2
      reasons.push('设备切换频繁')
    }
    
    // 检查地理位置跳跃
    if (behaviorData.locationJumpsPerDay > 3) {
      abnormalScore += 3
      reasons.push('地理位置跳跃异常')
    }
    
    return {
      isAbnormal: abnormalScore > 4,
      abnormalScore,
      reasons,
      recommendation: abnormalScore > 6 ? 'restrict' : abnormalScore > 4 ? 'monitor' : 'normal'
    }
  },

  /**
   * 生成安全评分
   * @param {object} userData 用户数据
   * @returns {object} 安全评分结果
   */
  generateSecurityScore(userData) {
    let score = 100 // 基础分数
    const deductions = []
    
    // 检查实名认证
    if (!userData.isRealNameVerified) {
      score -= 20
      deductions.push('未进行实名认证')
    }
    
    // 检查手机验证
    if (!userData.isPhoneVerified) {
      score -= 15
      deductions.push('未进行手机验证')
    }
    
    // 检查教育认证
    if (!userData.isEducationVerified) {
      score -= 10
      deductions.push('未进行教育认证')
    }
    
    // 检查工作认证
    if (!userData.isWorkVerified) {
      score -= 10
      deductions.push('未进行工作认证')
    }
    
    // 检查头像验证
    if (!userData.isAvatarVerified) {
      score -= 15
      deductions.push('未进行头像验证')
    }
    
    // 检查资料完整度
    const completeness = this.calculateProfileCompleteness(userData)
    if (completeness < 50) {
      score -= 15
      deductions.push('资料完整度低')
    }
    
    // 检查举报记录
    if (userData.reportCount > 0) {
      score -= userData.reportCount * 5
      deductions.push('存在举报记录')
    }
    
    // 检查违规记录
    if (userData.violationCount > 0) {
      score -= userData.violationCount * 10
      deductions.push('存在违规记录')
    }
    
    score = Math.max(0, score) // 确保分数不为负
    
    let level = 'low'
    if (score >= 80) level = 'high'
    else if (score >= 60) level = 'medium'
    
    return {
      score,
      level,
      deductions,
      suggestions: this.generateSecuritySuggestions(deductions)
    }
  },

  /**
   * 生成安全建议
   * @param {array} deductions 扣分项目
   * @returns {array} 安全建议列表
   */
  generateSecuritySuggestions(deductions) {
    const suggestions = []
    
    if (deductions.includes('未进行实名认证')) {
      suggestions.push('完成实名认证以提高账号安全性')
    }
    
    if (deductions.includes('未进行手机验证')) {
      suggestions.push('绑定并验证手机号码')
    }
    
    if (deductions.includes('未进行教育认证')) {
      suggestions.push('上传教育证明增加可信度')
    }
    
    if (deductions.includes('未进行工作认证')) {
      suggestions.push('验证工作信息提升专业形象')
    }
    
    if (deductions.includes('未进行头像验证')) {
      suggestions.push('进行头像真实性验证')
    }
    
    if (deductions.includes('资料完整度低')) {
      suggestions.push('完善个人资料信息')
    }
    
    if (deductions.includes('存在举报记录')) {
      suggestions.push('注意言行举止，避免被其他用户举报')
    }
    
    if (deductions.includes('存在违规记录')) {
      suggestions.push('严格遵守平台规则，避免违规行为')
    }
    
    return suggestions
  }
}

/**
 * 隐私保护工具
 */
const PrivacyProtection = {
  /**
   * 检查是否应该显示信息
   * @param {object} viewerData 查看者信息
   * @param {object} ownerData 信息所有者
   * @param {string} infoType 信息类型
   * @param {object} privacySettings 隐私设置
   * @returns {boolean} 是否允许显示
   */
  shouldShowInfo(viewerData, ownerData, infoType, privacySettings) {
    if (!viewerData || !ownerData || !privacySettings) return false
    
    // 自己查看自己的信息
    if (viewerData.userId === ownerData.userId) return true
    
    const visibility = privacySettings[`${infoType}Visibility`] || 'public'
    
    switch (visibility) {
      case 'public':
        return true
      case 'friends':
        return this.isFriend(viewerData.userId, ownerData.userId)
      case 'matched':
        return this.isMatched(viewerData.userId, ownerData.userId)
      case 'private':
        return false
      default:
        return false
    }
  },

  /**
   * 检查是否为好友
   * @param {string} userId1 用户1ID
   * @param {string} userId2 用户2ID
   * @returns {boolean} 是否为好友
   */
  isFriend(userId1, userId2) {
    // 这里应该调用实际的好友关系检查API
    // 暂时返回false作为示例
    return false
  },

  /**
   * 检查是否已匹配
   * @param {string} userId1 用户1ID
   * @param {string} userId2 用户2ID
   * @returns {boolean} 是否已匹配
   */
  isMatched(userId1, userId2) {
    // 这里应该调用实际的匹配关系检查API
    // 暂时返回false作为示例
    return false
  },

  /**
   * 过滤敏感信息
   * @param {object} userData 用户数据
   * @param {object} privacySettings 隐私设置
   * @param {object} viewerData 查看者信息
   * @returns {object} 过滤后的用户数据
   */
  filterSensitiveInfo(userData, privacySettings, viewerData) {
    const filtered = { ...userData }
    
    // 根据隐私设置掩码敏感信息
    if (privacySettings.maskPhoneNumber) {
      filtered.phoneNumber = DataMask.maskPhone(
        filtered.phoneNumber, 
        privacySettings.showPartialInfo
      )
    }
    
    if (privacySettings.maskEmail) {
      filtered.email = DataMask.maskEmail(
        filtered.email, 
        privacySettings.showPartialInfo
      )
    }
    
    if (privacySettings.maskRealName) {
      filtered.realName = DataMask.maskRealName(
        filtered.realName, 
        privacySettings.showPartialInfo
      )
    }
    
    // 根据关系隐藏距离信息
    if (!privacySettings.showDistance || 
        !this.shouldShowInfo(viewerData, userData, 'distance', privacySettings)) {
      delete filtered.distance
      delete filtered.location
    }
    
    // 根据设置隐藏在线状态
    if (!privacySettings.showOnlineStatus) {
      delete filtered.isOnline
      delete filtered.lastActive
    }
    
    // 根据设置隐藏最后在线时间
    if (!privacySettings.showLastSeen) {
      delete filtered.lastSeen
      delete filtered.lastActive
    }
    
    return filtered
  }
}

/**
 * 内容安全检查
 */
const ContentSecurity = {
  /**
   * 检查文本内容安全性
   * @param {string} content 文本内容
   * @returns {object} 检查结果
   */
  checkTextContent(content) {
    if (!content) return { isSafe: true, issues: [] }
    
    const issues = []
    let riskScore = 0
    
    // 检查敏感词
    const sensitiveWords = [
      '政治', '暴力', '色情', '毒品', '赌博', '诈骗',
      '传销', '邪教', '恐怖', '仇恨', '歧视'
    ]
    
    sensitiveWords.forEach(word => {
      if (content.includes(word)) {
        riskScore += 3
        issues.push(`包含敏感词: ${word}`)
      }
    })
    
    // 检查恶意内容
    const antiFraudResult = AntiFraud.detectSuspiciousText(content)
    if (antiFraudResult.isSuspicious) {
      riskScore += antiFraudResult.suspiciousScore
      issues.push(...antiFraudResult.reasons)
    }
    
    return {
      isSafe: riskScore < 5,
      riskScore,
      issues,
      recommendation: riskScore > 8 ? 'block' : riskScore > 5 ? 'review' : 'approve'
    }
  },

  /**
   * 过滤和清理文本内容
   * @param {string} content 原始内容
   * @param {boolean} strict 是否严格模式
   * @returns {string} 清理后的内容
   */
  sanitizeContent(content, strict = false) {
    if (!content) return ''
    
    let cleaned = content
    
    // 移除恶意标签
    cleaned = cleaned.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
    cleaned = cleaned.replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi, '')
    
    // 移除可疑链接
    cleaned = cleaned.replace(/https?:\/\/[^\s]+/gi, '[链接已移除]')
    
    if (strict) {
      // 严格模式下移除所有HTML标签
      cleaned = cleaned.replace(/<[^>]*>/g, '')
      
      // 移除可疑的联系方式
      cleaned = cleaned.replace(/\d{11}/g, '[手机号已隐藏]')
      cleaned = cleaned.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[邮箱已隐藏]')
    }
    
    return cleaned.trim()
  }
}

module.exports = {
  DataMask,
  AntiFraud,
  PrivacyProtection,
  ContentSecurity
}